package ar.com.huddleton.arquitectura;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.regex.Pattern;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Patterns;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import ar.com.huddleton.arquitectura.comun.FechasUtils;
import ar.com.huddleton.arquitectura.comun.iu.adaptadores.ListaSeccionadaAdapter;
import ar.com.huddleton.dummy.Evento;
import ar.com.huddleton.dummy.EventosDummy;

import com.google.android.gms.gcm.GoogleCloudMessaging;

public class ListadoHistoricos extends Activity {

	private List<Evento> resultadoEventos = null;
	private Context contexto = null;
	private ListView lista = null;
	String API_KEY = "388261167893";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        registrarEnGCM();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.listado_eventos);
        contexto = getApplicationContext();
        lista = (ListView) findViewById(R.id.lstEventosPrincipal);
        
        //TODO EN SQL
        resultadoEventos = EventosDummy.ITEMS;
        
        ListaSeccionadaAdapter adapter = new ListaSeccionadaAdapter(contexto, resultadoEventos);
        lista.setAdapter(adapter);
        
        registerForContextMenu(lista);
        lista.setOnCreateContextMenuListener(this);
        
    }
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
	private void registrarEnGCM() {
    	final Context context = getApplicationContext();
		new AsyncTask() {
			@Override
			protected Object doInBackground(Object... params) {
				GoogleCloudMessaging gcm=GoogleCloudMessaging.getInstance(context);
				String msg = "";
				try {
				
					String regid = gcm.register(API_KEY);
					msg = "Device registered, registration ID=" + regid;

					
					Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level
																	// 8+
					Account[] accounts = AccountManager.get(context)
							.getAccounts();
					String possibleEmail=null;
					for (Account account : accounts) {
						if (emailPattern.matcher(account.name).matches()) {
							possibleEmail = account.name;
							break;

						}
					}

					URL url = new URL(
							"http://huddlethon.appspot.com/registerDevice?mail="
									+ possibleEmail + "&regId=" + regid);
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setReadTimeout(10000 );
					conn.setConnectTimeout(15000 );
					conn.setDoInput(true);
					conn.connect();
					conn.getResponseCode();
					
					// Persist the regID - no need to register again.
					// storeRegistrationId(context, regid);
				} catch (IOException ex) {
					msg = "Error :" + ex.getMessage();
					// If there is an error, don't just keep trying to register.
					// Require the user to click a button again, or perform
					// exponential back-off.
				}
				return msg;
			}

			@Override
			protected void onPostExecute(Object msg) {
				Toast.makeText(context, "Aplicacion registrada", Toast.LENGTH_SHORT).show();
			}

		}.execute(null, null, null);
		
	}

	//Creacion del menu contextual para la lista
    @Override 
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { 
        super.onCreateContextMenu(menu, v, menuInfo); 
        MenuInflater inflater = getMenuInflater(); 
        menu.setHeaderTitle("Acciones disponibles"); 
        inflater.inflate(R.menu.menu_contextual_eventos, menu);
    }
    
    //Listener del evento item selected para el menu contextual de la lista
    @Override 
    public boolean onContextItemSelected(MenuItem item) {
    	
    	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); 
    	Evento eventoSeleccionado = ((Evento)lista.getAdapter().getItem(info.position)); 
    	
        switch (item.getItemId()) {
        	case R.id.ctxVerDetalle:
        		mostrarDialogoInfoEvento(eventoSeleccionado);
        		return true;
        	case R.id.ctxEliminar:
        		resultadoEventos.remove(eventoSeleccionado);
        		refrescarLista();
        		return true;
        	default:
        		return false;
        }
    }
    
    private void refrescarLista() {
    	ListaSeccionadaAdapter adapter = new ListaSeccionadaAdapter(contexto, resultadoEventos);
        lista.setAdapter(adapter);
    }
    
    private void mostrarDialogoInfoEvento(Evento eventoSeleccionado) {
    	
    	final Dialog infoEventoDialogo = new Dialog(this);
    	final RelativeLayout infoEvento = (RelativeLayout) getLayoutInflater().inflate(R.layout.informacion_evento_dialogo, null);
    	
    	((TextView) infoEvento.findViewById(R.id.txtResponsable)).setText(eventoSeleccionado.getResponsable().getNombre() + " " + eventoSeleccionado.getResponsable().getApellido());
    	((TextView) infoEvento.findViewById(R.id.txtNombreEvento)).setText(eventoSeleccionado.getAlimento().getTipoAlimento().toString());
    	((TextView) infoEvento.findViewById(R.id.txtFechaEvento)).setText(FechasUtils.fechaAString(eventoSeleccionado.getFecha(), 
    			FechasUtils.FECHA_CORTA_PATTERN));
    	((TextView) infoEvento.findViewById(R.id.txtMotivoEvento)).setText(eventoSeleccionado.getDescripcion());
    	    	
		((Button) infoEvento.findViewById(R.id.btnAceptarInfoDialogo)).setOnClickListener(new OnClickListener() {
    		public void onClick(View v) {
    			infoEventoDialogo.dismiss();
    		}
    	});
		
		infoEventoDialogo.setContentView(infoEvento);
		infoEventoDialogo.setTitle("Detalle de Evento");
		infoEventoDialogo.show();
    	
    }
    //Creacion del menu de la activity
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_listado_historicos, menu);
        return true;
    }
    
    //Listener para el evento item selected del menu de la activity
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_home:
            	finish();
                return true;
            default:
            	return true;
        }
    } 
}
